package client

import (
	"context"
	"google.golang.org/grpc"
	"week52/common/proto/class"
)

type Handler func(ctx context.Context, server class.ClassClient) (interface{}, error)

func ClassClient(ctx context.Context, handler Handler) (interface{}, error) {
	dial, err := grpc.Dial("127.0.0.1:8080", grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	client := class.NewClassClient(dial)
	res, err := handler(ctx, client)
	if err != nil {
		return nil, err
	}
	defer dial.Close()
	return res, nil
}

func AddClass(ctx context.Context, in *class.AddClassReq) (*class.AddClassResp, error) {
	client, err := ClassClient(ctx, func(ctx context.Context, server class.ClassClient) (interface{}, error) {
		addClass, err := server.AddClass(ctx, in)
		if err != nil {
			return nil, err
		}
		return addClass, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*class.AddClassResp), nil
}

func ClassDetail(ctx context.Context, in *class.ClassDetailReq) (*class.ClassDetailResp, error) {
	client, err := ClassClient(ctx, func(ctx context.Context, server class.ClassClient) (interface{}, error) {
		classDetail, err := server.ClassDetail(ctx, in)
		if err != nil {
			return nil, err
		}
		return classDetail, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*class.ClassDetailResp), nil
}

func AddClassOrder(ctx context.Context, in *class.AddClassOrderReq) (*class.AddClassOrderResp, error) {
	client, err := ClassClient(ctx, func(ctx context.Context, server class.ClassClient) (interface{}, error) {
		addClassOrder, err := server.AddClassOrder(ctx, in)
		if err != nil {
			return nil, err
		}
		return addClassOrder, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*class.AddClassOrderResp), nil
}

func TrueOrder(ctx context.Context, in *class.TrueOrderReq) (*class.TrueOrderResp, error) {
	client, err := ClassClient(ctx, func(ctx context.Context, server class.ClassClient) (interface{}, error) {
		addClassOrder, err := server.TrueOrder(ctx, in)
		if err != nil {
			return nil, err
		}
		return addClassOrder, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*class.TrueOrderResp), nil
}

func StatusOrderList(ctx context.Context, in *class.StatusOrderListReq) (*class.StatusOrderListResp, error) {
	client, err := ClassClient(ctx, func(ctx context.Context, server class.ClassClient) (interface{}, error) {
		addClassOrder, err := server.StatusOrderList(ctx, in)
		if err != nil {
			return nil, err
		}
		return addClassOrder, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*class.StatusOrderListResp), nil
}

func TellSmall(ctx context.Context, in *class.TellSmallReq) (*class.TellSmallResp, error) {
	client, err := ClassClient(ctx, func(ctx context.Context, server class.ClassClient) (interface{}, error) {
		addClassOrder, err := server.TellSmall(ctx, in)
		if err != nil {
			return nil, err
		}
		return addClassOrder, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*class.TellSmallResp), nil
}
